package demo.using.api.baidu;

import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author : GuoFei
 * @since : 2019/7/1 13:36
 */
public class BaiDuScanImg {

    public static void main(String[] args) {

        sample("dd");
    }

    public static AipOcr aipOcr = null;

    public static AipOcr initAipOcr(){
        if (aipOcr == null) {
            String appId = "16683900";
            String apiKey = "bE0YOuAPMEr1c0Y8veHwtL9z";
            String secretKey = "5QKDY7BpxCHvmYupwI2AbmaSPUaqzHn1";
            aipOcr =  new AipOcr(appId, apiKey, secretKey);
        }
        return aipOcr;
    }

    public static List<String> sample(String path) {
        AipOcr aipOcr = initAipOcr();
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");


        // 参数为本地路径
        JSONObject res = aipOcr.basicGeneral(path, options);
        System.out.println("response: "+res.toString(2));
        List<String> stringList = new ArrayList<>();
        res.getJSONArray("words_result").forEach(s->{
            stringList.add(((JSONObject) s).getString("words"));
        });
        stringList.forEach(System.out::println);
        return stringList;

        // 参数为二进制数组
//        byte[] bytes = image2Bytes("C:\\Users\\mayn\\Desktop\\88E0E04D-D37A-41cc-9C41-131C5A0977CA.png");
//        res = client.basicGeneral(bytes, options);
//        System.out.println(res.toString(2));

//        // 通用文字识别, 图片参数为远程url图片
//        JSONObject res = client.basicGeneralUrl(url, options);
//        System.out.println(res.toString(2));

    }

    static void buff2Image(byte[] b, String tagSrc) throws Exception {
        FileOutputStream fout = new FileOutputStream(tagSrc);
        //将字节写入文件
        fout.write(b);
        fout.close();
    }

    static byte[] image2Bytes(String imgSrc) throws Exception {
        FileInputStream fin = new FileInputStream(new File(imgSrc));
        //可能溢出,简单起见就不考虑太多,如果太大就要另外想办法，比如一次传入固定长度byte[]
        byte[] bytes = new byte[fin.available()];
        //将文件内容写入字节数组，提供测试的case
        fin.read(bytes);

        fin.close();
        return bytes;
    }

}
